// composables/useAnnouncement.ts

import { ref, reactive, onMounted } from 'vue';
import type { Announcement } from "@/interface/announcementData";
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/userStore';
export function useAnnouncement() {

  //数据定义==============================================================
  const userStore = useUserStore();
  const loading = ref(false);
  const noticeList = ref<Announcement[]>([]);
  const dialogVisible = ref(false);

  const form = reactive<Partial<Announcement>>({
    id: null,
    title: '',
    detaile: '',
    status: 'active',
    userIdentifier: null,
    createTime: new Date(),
    publishTime: new Date(),
  });

  // 后端请求==============================================
  async function REQ_getAllAnnouncement() {
    await axios.get("/api/announcement/allAnnouncement")
      .then(response => {
        console.log("公告数据：", response.data.data);
        noticeList.value = response.data.data;
      })
      .catch(error => {
        ElMessage.warning("获取公告，请求失败")
      })
  }

  async function REQ_saveOrUpdateAnnouncement(form: Announcement) {
    form.userIdentifier = userStore.useridentityfer;
    await axios.post("/api/announcement/saveAnnouncement", form)
      .then(response => {

      })
      .catch(error => {
        ElMessage.warning("保存或更新公告，请求失败")
      })
  }

  async function REQ_delAnnouncement(id: number) {
    await axios.get(`/api/announcement/delAnnouncement/${id}`)
      .then(response => {

      })
      .catch(error => {
        ElMessage.warning("公告删除，请求失败");
      })
  }

  async function REQ_updateStatusAnnouncement(id: number, status: string) {
    await axios.get(`/api/announcement/updateStatusAnnouncement/${id}/${status}`)
      .then(response => {

      })
      .catch(error => {
        ElMessage.warning("公告状态更新，请求失败");
      })
  }

  //=界面函数===================================================================== 
  // 加载公告
  const loadNotices = async () => {
    loading.value = true;
    await REQ_getAllAnnouncement();
    loading.value = false;
  };

  // 代开公告对话框
  const openDialog = (notice?: Announcement) => {
    if (notice) {
      Object.assign(form, notice);
    } else {
      Object.assign(form, {
        id: null,
        title: '',
        detaile: '',
        status: 'active',
        userIdentifier: null,
        createTime: new Date(),
        publishTime: new Date(),
      });
    }
    dialogVisible.value = true;
  };

  // 保存或者跟新公告
  const saveNotice = async () => {
    await REQ_saveOrUpdateAnnouncement(form);
    if (form.id) {
      const index = noticeList.value.findIndex(n => n.id === form.id);
      if (index !== -1) {
        noticeList.value.splice(index, 1, { ...(form as Announcement) });
      }
    } else {
      noticeList.value.push({ ...(form as Announcement) });
    }
    dialogVisible.value = false;
  };

  // 删除公告
  const deleteNotice = async (id: number) => {
    await REQ_delAnnouncement(id);
    noticeList.value = noticeList.value.filter(n => n.id !== id);
  };

  // 修改公告状态
  const toggleStatus = async (row: Announcement) => {
    row.status = row.status === 'active' ? 'inactive' : 'active';
    await REQ_updateStatusAnnouncement(row.id as number, row.status as string);

  };

  onMounted(loadNotices);

  return {
    loading,
    noticeList,
    dialogVisible,
    form,
    openDialog,
    saveNotice,
    deleteNotice,
    toggleStatus,
  };
}
